local dx_net = require("dx_net")
local dx_map = require("dx_map")
local dx_mapping = require("mapping")
local log = require("mylog")
local dx_json = require("dx_json")
local dx_gpio = require("dx_gpio")
local config = require("config")

local network_service = {}

-- 未初始态
local VBAR_NET_STATUS_NONE = 0
-- 网卡处于关闭状态
local VBAR_NET_STATUS_DOWN = 1
-- 网卡处于打开状态
local VBAR_NET_STATUS_UP = 2
-- 网线已插入或者wifi已连接ssid 但未分配ip
local VBAR_NET_STATUS_CONNECTING_ROUTE = 3
-- 已成功分配ip
local VBAR_NET_STATUS_CONNECTED_ROUTE = 4
-- 已连接指定服务或者通过测试可以连接到广域网
local VBAR_NET_STATUS_CONNECTED_SERVER = 5

-- 加载net
function network_service.config_net()
    log.info("[config_net]网络配置初始化")
    log.info("[config_net]网络配置初始化")
    dx_net.net_init()
    dx_net.vbar_net_card_enable()
    local net_static_param = nil
    dx_net.vbar_net_set_mode_by_card(2, net_static_param)
    -- 注册网络状态回调
    dx_net.net_status_callback_register(network_service.func_cb)
    -- 重新配置网络信息
    network_service.config_network()
end

-- 更新配置信息
function network_service.config_network()
    local net_param = dx_net.vbar_net_get_mode_by_card()
    while 1 do
        if string.byte(string.char(net_param.ip[1])) ~= 0 then
            config.configStrToTable()
            -- 获取到信息
            g_config["local_ip"] = network_service.toAscii(net_param.ip, 20)
            g_config["local_gateway"] = network_service.toAscii(net_param.gateway, 20)
            g_config["local_dns"] = network_service.toAscii(net_param.dns0, 20)
            g_config["local_netmask"] = network_service.toAscii(net_param.netmask, 20)
            -- 持久化数据
            ret = writecfg()
            if ret ~= 0 then
                log.debug("[config_network]数据保存失败！")
            else
                log.debug("[config_network]数据保存成功！ ")
            end
            -- 把最新的配置信息存储到全局MAP中
            config.configTableToStr()
            break
        end
        net_param = dx_net.vbar_net_get_mode_by_card()
        os.execute("sleep 1")
    end
end

-- 网络状态回调函数
function network_service.func_cb(type, status, pdata)
    if status == VBAR_NET_STATUS_NONE then
        print(type, status, pdata)
    elseif status == VBAR_NET_STATUS_DOWN then
        print(type, status, pdata)
    elseif status == VBAR_NET_STATUS_UP then
        print(type, status, pdata)
    elseif status == VBAR_NET_STATUS_CONNECTING_ROUTE then
        print(type, status, pdata)
    elseif status == VBAR_NET_STATUS_CONNECTED_ROUTE then
        print(type, status, pdata)
        config.configStrToTable()
        g_config["network_status"] = true
        config.configTableToStr()
        if g_config["mqtt_con_status"] then
            dx_gpio.gpio_set_value(73, 1)
        end
    elseif status == VBAR_NET_STATUS_CONNECTED_SERVER then
        print(type, status, pdata)
    end
    if status ~= VBAR_NET_STATUS_CONNECTED_ROUTE then
        dx_gpio.gpio_set_value(73, 0)
    end
end

-- NET配置信息变更后，重新配置网络
function network_service.reconfig_net_by_config(net_info)
    dx_net.net_init()
    dx_net.vbar_net_card_enable()
    local netConfig = {}
    for k, v in pairs(dx_mapping.netQrToConfigMapping) do
        netConfig[v] = net_info[k]
    end
    for k, v in pairs(dx_mapping.netPaasToConfigMapping) do
        netConfig[v] = net_info[k]
    end

    local net_static_param = {
        ip = netConfig["local_ip"],
        gateway = netConfig["local_gateway"],
        netmask = netConfig["local_netmask"],
        dns0 = netConfig["local_dns"],
        dns1 = netConfig["local_dns"]
    }
    local net_mode = 1
    if netConfig["isDHCPMod"] then
        net_mode = 0
    end
    local net_static_param_str = dx_json.encode(net_static_param)
    log.info("[reconfig_net_by_config]net_static_param_str: ", net_static_param_str)
    log.info("[reconfig_net_by_config]net_static_param_str: ", net_mode)
    local set_net_status = dx_net.vbar_net_set_mode_by_card(net_mode, net_static_param)
    log.info("[reconfig_net_by_config]NET配置变化-重新配置网络")
    dx_map.remove(_G["_G_map"], "net_info_str")
end

-- 监听全局Map，检测NET配置信息是否变化
function network_service.reConfigNet()
    local net_info_str = dx_map.get(_G["_G_map"], "net_info_str")
    log.info("[reConfigNet]")
    if net_info_str ~= nil and string.len(net_info_str) > 0 then
        local net_info = dx_json.decode(net_info_str)
        if net_info ~= nil then
            network_service.reconfig_net_by_config(net_info)
        end
    end
end

function network_service.toAscii(strings, len)
    local i = 0
    local str = ""
    while i < len do
        -- 跳过空白字符
        if string.byte(string.char(strings[i])) ~= 0 then
            str = str .. string.char(strings[i])
        end
        i = i + 1
    end
    return str
end

return network_service
